package com.examplemartin.jpademo.interceptor;

import com.examplemartin.jpademo.constant.Session_Constant;
import com.examplemartin.jpademo.pojo.po.MenuPO;
import com.examplemartin.jpademo.pojo.po.UserPO;
import com.examplemartin.jpademo.pojo.vo.MenuVO;
import com.examplemartin.jpademo.service.admin.MenuService;
import com.examplemartin.jpademo.util.MenuUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * 登入拦截器
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Resource
    private MenuService menuService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        HttpSession session = request.getSession();
        String requestURI = request.getRequestURI();
        // 用户第一次访问或未登入
        if (session == null || session.getAttribute(Session_Constant.SESSION_LOING_USER_KEY) == null) {

            response.sendRedirect("/sys/login.do");

            return false;
        }

        UserPO user = (UserPO) session.getAttribute(Session_Constant.SESSION_LOING_USER_KEY);

        // supreme 开发测试使用
        if (user.getRole().getName().equals("supreme")) {
            List<MenuPO> menuList = menuService.getMenuList();
            List<MenuVO> suprememenu = MenuUtil.assembleMenuList(menuList);
            session.setAttribute("userauthlist", suprememenu);
            return true;
        }

// END supreme 开发测试使用
        List<MenuPO> authorities = user.getRole().getAuthorities();
        List<MenuVO> authlist = MenuUtil.assembleMenuList(authorities);
        session.setAttribute("userauthlist", authlist);
        return true;
    }
}
